package com.zr.influx.service;
import com.zr.influx.model.ForexData;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 外汇行情数据生成服务，负责模拟生成真实的外汇行情数据
 */
@Service
public class ForexDataGenerator {

    // 主要货币对列表
    private static final List<String> CURRENCY_PAIRS = Arrays.asList(
            "EUR/USD", "USD/JPY", "GBP/USD", "USD/CHF",
            "AUD/USD", "USD/CAD", "USD/HKD", "EUR/GBP"
    );

    // 模拟的交易所列表
    private static final List<String> EXCHANGES = Arrays.asList(
            "FOREX.com", "IG", "OANDA", "Saxo Bank", "XTB"
    );

    private final Random random = new Random();
    // 跟踪每种货币对的当前价格，确保价格波动的连续性
    private final Map<String, Double> priceTracker = new ConcurrentHashMap<>();

    /**
     * 生成所有货币对的行情数据
     */
    public List<ForexData> generateAllCurrencyPairsData() {
        List<ForexData> dataList = new ArrayList<>();
        for (String currencyPair : CURRENCY_PAIRS) {
            dataList.add(generateForexData(currencyPair));
        }
        return dataList;
    }

    /**
     * 生成单个货币对的行情数据
     */
    public ForexData generateForexData(String currencyPair) {
        // 获取当前价格，如果没有则初始化
        double currentPrice = priceTracker.getOrDefault(currencyPair, 0.0);
        if (currentPrice == 0) {
            currentPrice = initializePrice(currencyPair);
        }

        // 生成价格波动 (-0.5% 到 +0.5% 之间)
        double changePercent = (random.nextDouble() - 0.5) * 0.01; // -0.5% 到 0.5%
        double newPrice = currentPrice * (1 + changePercent);

        // 生成开盘价、最高价、最低价
        double openPrice = currentPrice;
        double highPrice = Math.max(openPrice, newPrice) * (1 + random.nextDouble() * 0.002);
        double lowPrice = Math.min(openPrice, newPrice) * (1 - random.nextDouble() * 0.002);
        double closePrice = newPrice;

        // 生成成交量 (10万到100万之间)
        long volume = 100000 + (long) (random.nextDouble() * 900000);

        // 随机选择一个交易所
        String exchange = EXCHANGES.get(random.nextInt(EXCHANGES.size()));

        // 更新当前价格
        priceTracker.put(currencyPair, closePrice);

        // 返回生成的行情数据
        return new ForexData(
                currencyPair,
                exchange,
                openPrice,
                highPrice,
                lowPrice,
                closePrice,
                volume,
                Instant.now()
        );
    }

    /**
     * 根据货币对类型初始化价格
     */
    private double initializePrice(String currencyPair) {
        if (currencyPair.contains("JPY")) {
            return 100 + random.nextDouble() * 50; // 日元相关货币对价格较高
        } else if (currencyPair.contains("HKD") || currencyPair.contains("CAD")) {
            return 0.7 + random.nextDouble() * 0.5;
        } else {
            return 0.8 + random.nextDouble() * 0.6;
        }
    }
}
